var prefix = jsctx + "/channel/apply";

var channel = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                channelName: $('#channelName').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageChannelApply",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 10,
                    pageList: [10],
                    pageNumber: 1,
                    sidePagination: "server",
                    cache: false,
                    paginationShowPageGo: true,
                    rightFixedColumns: false,
                    queryParams: function (params) {
                        return {
                            pageSize: params.limit,
                            pageNo: (params.offset / params.limit) + 1,
                            channelName: $("#channelName").val()
                        };
                    },
                    columns: [
                        {
                            title: 'id', field: '', width: '50', align: 'center',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'channelApplyId', title: '渠道商ID', width: '100', align: 'center'},
                        {field: 'channelName', title: '渠道商名称', width: '100', align: 'center'},
                        {field: 'channelLevel', title: '等级', width: '100', align: 'center'},
                        {field: 'recommenderId', title: '推荐人ID', width: '100', align: 'center'},
                        {field: 'principal', title: '负责人', width: '100', align: 'center'},
                        {field: 'mobile', title: '联系电话', width: '100', align: 'center'},
                        {field: 'createdTime', title: '创建时间', width: '100', align: 'center'},
                        {
                            field: 'applyStatus',
                            title: '审核状态',
                            width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span class="label label-success">待审核</span>';
                                } else if (value == '1') {
                                    return '<span class="label label-info">审核通过</span>';
                                } else if (value == '2') {
                                    return '<span class="label label-danger">审核未通过</span>';
                                }
                            }
                        },
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                var operate = "";
                                var a = '<a class="btn btn-primary btn-sm' + has_edit + '" href="#" title="审核" onclick="channel.showModel(\''
                                    + row.channelApplyId + '\')">审核</a> ';
                                var b = '<a class="btn btn-primary btn-sm' + has_edit + '" href="#" title="编辑" onclick="channel.edit(\''
                                    + row.channelApplyId + '\')">编辑</a> ';
                                var c = '<a class="btn btn-primary btn-sm' + has_edit + '" href="#" title="详情" onclick="channel.detail(\''
                                    + row.channelApplyId + '\')">详情</a> ';
                                var d = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="删除" onclick="channel.delete(\''
                                    + row.channelApplyId + '\')">删除</a> ';
                                if (row.applyStatus == '0') {
                                    operate = operate + a;
                                }

                                return operate + b + c + d;

                            }
                        }
                    ], onLoadSuccess: function () {
                        initSwitch();
                    }, onPageChange: function () {
                        initSwitch();
                    }
                });
    }

    function initSwitch() {
        $("[name='notice-status']").bootstrapSwitch({
            onText: "启用",      // 设置ON文本
            offText: "禁用",    // 设置OFF文本
            onColor: "primary",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size: "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            hadleWidth: "20",
            // 当开关状态改变时触发
            onSwitchChange: function (event, state) {
                //修改操作
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: prefix + "/udpateContentStatus",
                    data: {
                        status: state ? 0 : 1,
                        id: this.value
                    },
                    success: function (data) {
                        $('#TestTables').bootstrapTable('refresh'); //Table页面刷新
                    },
                    error: function (xhr, error, exception) {
                        let errorMsg = xhr.responseText;
                        openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
                    }
                });
            }
        })
    }

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    }

    function add() {
        location.href = prefix + "/add";
    }

    function edit(id) {
        location.href = prefix + "/edit/" + id;
    }

    function detail(id) {
        location.href = prefix + "/detail/" + id;
    }

    function deleteChannel(id) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/delete",
                type: "post",
                data: {
                    'id': id
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }


    function goBack() {
        window.history.back();
    }

    /*  模态框  */
    function showModel(id) {
        $('#exampleModal').modal('show');

        $("#submitButton").unbind("click").bind("click", function () {
            $.ajax({
                url: prefix + "/updateChannelApplyForAudit",
                type: "post",
                data: {
                    "id": id,
                    "status": $("#status").val(),
                    "remark": $("#remark").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                    }
                }
            })
        })

    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        add: add,
        edit: edit,
        showModel: showModel,
        detail: detail,
        exportList: exportList,
        delete: deleteChannel
    };
})();

var addChannel = (function () {
    function init() {
        validateRule();
    };


    var isajaxsend = true;

    function save() {
        var formData = new FormData($("#frm")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/addChannelApply",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            beforeSend: function () {
                isajaxsend = false
            },
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    window.history.back();
                } else {
                    parent.layer.alert(data.message)
                }

            },
            complete: function () {
                isajaxsend = false
            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                channelName: {
                    required: true
                },
                principal: {
                    required: true
                },
                mobile: {
                    required: true
                }

            },
            messages: {
                channelName: {
                    required: icon + "请输入渠道商名称"
                },principal: {
                    required: icon + "请输入负责人"
                },mobile: {
                    required: icon + "请输入联系电话"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();

var editChannel = (function () {
    function init() {
        validateRule();
    };


    var isajaxsend = true;

    function save() {
        var formData = new FormData($("#frm")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/updateChannelApply",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            beforeSend: function () {
                isajaxsend = false
            },
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    javascript:history.back(-1);
                } else {
                    parent.layer.alert(data.message)
                }

            },
            complete: function () {
                isajaxsend = false
            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                channelName: {
                    required: true
                },
                principal: {
                    required: true
                },
                mobile: {
                    required: true
                }

            },
            messages: {
                channelName: {
                    required: icon + "请输入渠道商名称"
                },principal: {
                    required: icon + "请输入负责人"
                },mobile: {
                    required: icon + "请输入联系电话"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();

